package netty.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author cyt
 * @create 2020-11-05 12:09
 */
public class GroupClientTwo {
    private final String HOST = "127.0.0.1";
    private final String PORT = "6667";
    private SocketChannel socketChannel;
    private String username;
    private Selector selector;

    /**
     * 为当前的selector和channel设置初始化值
     *
     * @throws IOException
     */
    public GroupClientTwo() throws IOException {
        selector = Selector.open();
        socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", Integer.parseInt(PORT)));
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + " is ok !");
    }

    public void sendInfo(String info) {
        info = username + "speak : " + info;
        try {
            /**
             * 把要发送的消息通过内存块写入到通道中。
             */
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void readInfo() {
        try {
            /**
             * 得到当前所有可用的通道，并且开始遍历通道
             * 如果当前通道是可以读的， 就开启一个内存块
             * 把通道中的数据写入到内存块中！
             */
            int readChannels = selector.select();
            if (readChannels > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        SocketChannel sc = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        sc.read(buffer);
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
                iterator.remove();
            } else {
                System.out.println("没有可用的通道");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        GroupClientTwo groupClient = new GroupClientTwo();
        // 开启一个线程一直在读取数据
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    groupClient.readInfo();
                    try {
                        sleep(3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            groupClient.sendInfo(s);
        }
    }
}
